using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace SchoolApp_Material.ViewModels;

public partial class PaginationViewModel : ViewModelBase, INotifyDataErrorInfo
{
    private Action _executeAction;
    
    public PaginationViewModel(Action executeAction)
    {
        _executeAction = executeAction;
    }
    
    #region 属性
    
    [ObservableProperty] private int _pageSize = 10;
    
    private int _pageNo = 1;
    
    public int PageNo
    {
        get => _pageNo;
        set
        {
            SetProperty(ref _pageNo, value);
            RefreshCommand();
        }
    }
    
    
    private int _pageCount = 1;
    
    public int PageCount
    {
        get => _pageCount;
        set
        {
            SetProperty(ref _pageCount, value);
            RefreshCommand();
        }
    }
    
    
    [ObservableProperty] private long _rowCount;
    
    #endregion
    
    #region 命令
    
    [RelayCommand(CanExecute = nameof(CanFirstPage))]
    private void FirstPage()
    {
        PageNo = 1;
        _executeAction?.Invoke();
    }
    
    private bool CanFirstPage()
    {
        return PageNo > 1;
    }
    
    [RelayCommand(CanExecute = nameof(CanPrevPage))]
    private void PrevPage()
    {
        PageNo--;
        _executeAction?.Invoke();
    }
    
    private bool CanPrevPage()
    {
        return PageNo > 1;
    }
    
    [RelayCommand(CanExecute = nameof(CanNextPage))]
    private void NextPage()
    {
        PageNo++;
        _executeAction?.Invoke();
    }
    
    private bool CanNextPage()
    {
        return PageNo < PageCount;
    }
    
    [RelayCommand(CanExecute = nameof(CanEndPage))]
    private void EndPage()
    {
        PageNo = PageCount;
        _executeAction?.Invoke();
    }
    
    private bool CanEndPage()
    {
        return PageNo < PageCount;
    }
    
    #endregion
    
    #region 方法
    
    private void RefreshCommand()
    {
        FirstPageCommand.NotifyCanExecuteChanged();
        PrevPageCommand.NotifyCanExecuteChanged();
        NextPageCommand.NotifyCanExecuteChanged();
        EndPageCommand.NotifyCanExecuteChanged();
    }
    
    #endregion
    
    #region INotifyDataErrorInfo 实现
    
    private readonly Dictionary<string, List<string>> _errors = new();
    
    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
    public bool HasErrors => _errors.Any();
    
    public IEnumerable GetErrors(string? propertyName) =>
        propertyName != null && _errors.TryGetValue(propertyName, out var errors)
            ? errors
            : Enumerable.Empty<string>();
    
    #endregion
}